package com.wie.controller;

import com.wie.domain.dto.LoginDTO;
import com.wie.domain.entity.Login;
import com.wie.domain.entity.Result;
import com.wie.domain.vo.LoginVO;
import com.wie.properties.JwtProperties;
import com.wie.service.LoginService;
import com.wie.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@Slf4j
@RestController
@RequestMapping("/login")
@CrossOrigin(allowCredentials = "true", allowedHeaders = "true")
public class LoginController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 用户登录
     * @param loginDTO
     * @return
     */
    @PostMapping
    public Result login(@RequestBody LoginDTO loginDTO){
        log.info("登录：{}", loginDTO.getUsername());
        //校验用户
        Login loginUser = loginService.login(loginDTO);
        //登录成功，生成令牌
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("id", loginUser.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getSignKey(),
                jwtProperties.getExpire(),
                claims);
        //封装VO对象
        LoginVO loginVO = LoginVO.builder()
                .token(token)
                .build();
        return Result.success(loginVO);
    }
}
